/*

 * Licensed to the Apache Software Foundation (ASF) under one

 * or more contributor license agreements.  See the NOTICE file

 * distributed with this work for additional information

 * regarding copyright ownership.  The ASF licenses this file

 * to you under the Apache License, Version 2.0 (the

 * "License"); you may not use this file except in compliance

 * with the License.  You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package com.bff.gaia.unified.sdk.extensions.sql;



import com.bff.gaia.unified.sdk.Pipeline;

import com.bff.gaia.unified.sdk.annotations.Experimental;

import com.bff.gaia.unified.sdk.extensions.sql.impl.UnifiedSqlEnv;

import com.bff.gaia.unified.sdk.extensions.sql.impl.ParseException;

import com.bff.gaia.unified.sdk.extensions.sql.impl.rel.UnifiedEnumerableConverter;

import com.bff.gaia.unified.sdk.extensions.sql.impl.rel.UnifiedSqlRelUtils;

import com.bff.gaia.unified.sdk.extensions.sql.meta.store.MetaStore;

import com.bff.gaia.unified.sdk.options.PipelineOptions;



/** {@link UnifiedSqlCli} provides methods to execute Unified SQL with an interactive client. */

@Experimental

public class UnifiedSqlCli {

  private UnifiedSqlEnv env;

  /** The store which persists all the table meta data. */

  private MetaStore metaStore;



  public UnifiedSqlCli metaStore(MetaStore metaStore) {

    return metaStore(metaStore, false);

  }



  public UnifiedSqlCli metaStore(MetaStore metaStore, boolean autoLoadUdfUdaf) {

    this.metaStore = metaStore;

    UnifiedSqlEnv.UnifiedSqlEnvBuilder builder = UnifiedSqlEnv.builder(metaStore);

    if (autoLoadUdfUdaf) {

      builder.autoLoadUserDefinedFunctions();

    }

    this.env = builder.build();

    return this;

  }



  public MetaStore getMetaStore() {

    return metaStore;

  }



  /** Returns a human readable representation of the query execution plan. */

  public String explainQuery(String sqlString) throws ParseException {

    return env.explain(sqlString);

  }



  /** Executes the given sql. */

  public void execute(String sqlString) throws ParseException {



    if (env.isDdl(sqlString)) {

      env.executeDdl(sqlString);

    } else {

      PipelineOptions options =

          UnifiedEnumerableConverter.createPipelineOptions(env.getPipelineOptions());

      options.setJobName("UnifiedPlanCreator");

      Pipeline pipeline = Pipeline.create(options);

      UnifiedSqlRelUtils.toPCollection(pipeline, env.parseQuery(sqlString));

      pipeline.run();

    }

  }

}